<template>
    <div class="container">
        <Alert type="error" show-icon closable v-if="validate.isShow">
            {{validate.message}}
        </Alert>
        <div class="ask">
            <Input v-model="form.title" placeholder="用一句话描述问题，并以问好结尾" @on-keyup="titleRemain" :maxlength="titleInputMax">
              <Select v-model="form.sort" slot="prepend" style="width: 80px" placeholder="分类" :label-in-value="true" @on-change="triggerCategory">
                  <Option v-for="(category, index) in categoryList" v-bind:key="index" :value="category.id">{{category.categoryName}}</Option>
              </Select>
            </Input>
            <div class="text-remain" v-if="titleTextRemain < 50">您还能输入
                <span>{{titleTextRemain}}</span>个字</div>
            </div>
        <div id="editor"></div>
        <div class="btn-action">
            <Button type="primary" :loading="loading" @click="onSubmit" size="large" styles="color:#fff;margin:auto;">
                <span v-if="!loading" style="color:#fff;">提交</span>
                <span v-else>提交中</span>
            </Button>
        </div>
    </div>
</template>

<script>
import ZhidaoAPI from "@/api/zhidao/ZhidaoAPI";
import axios from "axios";
import xss from "xss";
// 创建编辑器
import E from "wangeditor";
var editor = new E("#editor");
editor.customConfig.menus = [
  "head", // 标题
  "bold", // 粗体
  "underline", // 下划线
  "foreColor", // 文字颜色
  "link", // 插入链接
  "justify", // 对齐方式
  'emoticon',  // 表情
  "quote", // 引用
  "image", // 插入图片
  "code", // 插入代码
  'undo',  // 撤销
  'redo',  // 重复
];
// 下面两个配置，使用其中一个即可显示“上传图片”的tab。但是两者不要同时使用！！！
// editor.customConfig.uploadImgShowBase64 = true   // 使用 base64 保存图片
// 上传图片请求地址
editor.customConfig.uploadImgServer = ZhidaoAPI.upload_image + "/answer";
// 图片大小限制为 10M
editor.customConfig.uploadImgMaxSize = 10 * 1024 * 1024;
// 限制一次最多上传 1 张图片
editor.customConfig.uploadImgMaxLength = 1;
// 可自定义filename
editor.customConfig.uploadFileName = "file";
// 设置上传超时时间改为 60s
editor.customConfig.uploadImgTimeout = 60000;
// 隐藏“网络图片”tab
editor.customConfig.showLinkImg = false;
export default {
  name: "AskQuestion",
  data() {
    return {
      categoryList: [],
      form: {
        title: "",
        sort: ""
      },
      titleInputMax: 50,
      titleMaxLength: 50,
      titleTextRemain: 50,
      loading: false,
      validate: {
        isShow: false,
        message: ""
      }
    };
  },
  mounted() {
    editor.customConfig.zIndex = 9;
    editor.create();
    this.fetchCatetory();
    let selectedCategory = this.$route.params.searchIndex;
    if (selectedCategory != 0) {
      this.form = Object.assign(
        {},
        {
          title: "",
          sort: selectedCategory
        }
      );
    }
  },
  methods: {
    fetchCatetory() {
        axios
        .get(ZhidaoAPI.fetch_category)
        .then((resp)=> {
           this.categoryList = resp.data.categoryDTOList;
        })
        .catch((error)=>{
           this.$Message.error("操作失败【" + error + "】");
        });
    },
    triggerCategory(labelInValue) {
      this.form.sort = labelInValue.value;
    },
    // 表单提交
    onSubmit() {
      // 验证
      let title = this.form.title,
        sort = xss(this.form.sort),
        content = xss(editor.txt.html());
      if (content == null || content == "<p><br></p>") {
        this.$Message.warning("写点东西呗");
        return;
      }
      let verify = this.verifyForm(title, sort, content);
      if (!verify) {
        return;
      }
       axios
        .post(ZhidaoAPI.save_question, {
          categoryId: sort,
          title: title,
          question: content
        })
        .then((resp)=>{
          if ("0000" == resp.data.code) {
            // 成功
            this.loading = false;
            this.form.sort = "";
            this.form.title = "";
            editor.txt.clear();
            this.$Message.success("提交成功");
            this.$router.push("/Know-how/Answers");
          } else {
            this.$Message.error(resp.data.message);
          }
        })
        .catch((error)=>{
           this.$Message.error("操作失败【" + error + "】");
        });
    },
    // 表单验证
    verifyForm(title, sort, content) {
      if (!sort) {
        this.alertText(true, "请选择分类");
        return false;
      }
      if (!title) {
        this.alertText(true, "请填写标题");
        return false;
      }
      if (!content) {
        this.alertText(true, "请填写内容");
        return false;
      }
      return true;
    },
    // 错误提示通用方法
    alertText(isShow, message) {
      this.validate = {
        isShow,
        message
      };
    },
    // 标题字数剩余显示计算
    titleRemain(e) {
      let titleLen = this.form.title.split("").length;
      this.titleTextRemain = this.titleMaxLength - titleLen;
    }
  }
};
</script>
<style scoped>
.container {
  width: 70vw;
  margin: 0 auto;
  margin-top: 80px;
}

.ask {
  margin: 20px 0;
}
.text-remain {
  line-height: 3;
  padding-left: 86px;
}
span {
  color: red;
}

.btn-action {
  width: 70vw;
  margin: 0 auto;
  margin-top: 40px;
}
</style>
